package com.edgar.music.network;

import android.content.Context;
import android.util.Log;

import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;

/**
 * Created by Edgar on 2017/1/2.
 * 请求帮助类
 */
public final class RequestHelper {

    private static final String TAG = "RequestHelper";
    private Retrofit mRetrofit;
    private Context mContext;
    private RequestHelper(){}

    public static RequestHelper getInstance(){
        return InstanceHolder.instance;
    }

    private static class InstanceHolder{
        private static RequestHelper instance = new RequestHelper();
    }

    public void init(Context context,String url){
        if (mContext != null) return;
        mContext = context.getApplicationContext();
        Retrofit.Builder builder = new Retrofit.Builder();
        builder.baseUrl(url);
        builder.addConverterFactory(GsonConverterFactory.create());
        mRetrofit = builder.build();
    }

    public Retrofit getRetrofit() {
        return mRetrofit;
    }

    public <T> T getApiService(Class<T> clazz){
        return mRetrofit.create(clazz);
    }

    public <T> void handlerSuccess(Response<T> response, RequestCallback<T> callback){
        if (response == null || callback == null) return;
        Log.i(TAG,String.format("Response:state:%s,protocol:%s",response.code(),response.raw().protocol().name()));
        if (response.isSuccess()){
            T musicResponse = response.body();
            callback.onSuccess(musicResponse);
        } else {
            callback.onFailure(response.code(),response.message());
        }
    }

    public <T> void handlerThrowable(Throwable e,RequestCallback<T> callback){
        if (callback != null){
            callback.onException(e);
        }
    }
}